```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>深入理解公平锁与非公平锁 | 并发编程核心机制</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <link href="https://cdn.staticfile.org/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.staticfile.org/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/mermaid@latest/dist/mermaid.min.js"></script>
    <style>
        body {
            font-family: 'Noto Sans SC', 'Helvetica Neue', Arial, sans-serif;
            color: #333;
            background-color: #f9fafb;
            line-height: 1.6;
        }
        .hero-gradient {
            background: linear-gradient(135deg, #6e8efb 0%, #a777e3 100%);
        }
        .code-block {
            background-color: #2d3748;
            border-radius: 0.5rem;
            padding: 1.5rem;
            position: relative;
        }
        .code-block pre {
            margin: 0;
            color: #e2e8f0;
            overflow-x: auto;
        }
        .code-block .language {
            position: absolute;
            top: 0;
            right: 1rem;
            background-color: #4a5568;
            color: white;
            padding: 0.25rem 0.75rem;
            border-bottom-left-radius: 0.25rem;
            border-bottom-right-radius: 0.25rem;
            font-size: 0.875rem;
        }
        .card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            border-radius: 0.75rem;
            overflow: hidden;
        }
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        .divider {
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(0,0,0,0.1), transparent);
            margin: 3rem 0;
        }
        .drop-cap:first-letter {
            float: left;
            font-size: 3.5rem;
            line-height: 1;
            margin: 0 0.5rem 0 0;
            color: #6e8efb;
            font-weight: bold;
        }
        .comparison-table {
            border-collapse: collapse;
            width: 100%;
        }
        .comparison-table th, .comparison-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
        }
        .comparison-table th {
            background-color: #f7fafc;
            font-weight: 600;
            color: #4a5568;
        }
        .comparison-table tr:hover td {
            background-color: #f7fafc;
        }
        .mermaid-container {
            background-color: white;
            padding: 2rem;
            border-radius: 0.75rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
        .nav-link {
            position: relative;
        }
        .nav-link:after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 0;
            height: 2px;
            background-color: #6e8efb;
            transition: width 0.3s ease;
        }
        .nav-link:hover:after {
            width: 100%;
        }
    </style>
</head>
<body class="antialiased">
    <!-- Hero Section -->
    <section class="hero-gradient text-white py-20 px-4 md:px-0">
        <div class="container mx-auto max-w-5xl">
            <div class="flex flex-col md:flex-row items-center">
                <div class="md:w-1/2 mb-10 md:mb-0">
                    <h1 class="text-4xl md:text-5xl font-bold mb-6 font-serif">公平锁与非公平锁</h1>
                    <p class="text-xl opacity-90 mb-8 leading-relaxed">多线程环境下的资源访问策略与性能权衡</p>
                    <div class="flex space-x-4">
                        <a href="#basic-concepts" class="bg-white text-indigo-700 px-6 py-3 rounded-lg font-medium hover:bg-opacity-90 transition duration-300">开始探索</a>
                        <a href="#comparison" class="border border-white px-6 py-3 rounded-lg font-medium hover:bg-white hover:bg-opacity-10 transition duration-300">直接比较</a>
                    </div>
                </div>
                <div class="md:w-1/2 flex justify-center">
                    <div class="bg-white bg-opacity-20 p-6 rounded-2xl backdrop-filter backdrop-blur-sm">
                        <div class="mermaid-container">
                            <div class="mermaid">
                                flowchart LR
                                    A[锁机制] --> B[公平锁]
                                    A --> C[非公平锁]
                                    B --> D[先进先出 FIFO]
                                    B --> E[避免饥饿]
                                    B --> F[性能较低]
                                    C --> G[允许插队]
                                    C --> H[高吞吐量]
                                    C --> I[可能饥饿]
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Navigation -->
    <nav class="bg-white shadow-sm sticky top-0 z-10">
        <div class="container mx-auto max-w-5xl px-4">
            <div class="flex justify-between items-center py-4">
                <div class="text-xl font-bold text-indigo-700">并发编程指南</div>
                <div class="hidden md:flex space-x-8">
                    <a href="#basic-concepts" class="nav-link text-gray-700 hover:text-indigo-700">基本概念</a>
                    <a href="#fair-lock" class="nav-link text-gray-700 hover:text-indigo-700">公平锁</a>
                    <a href="#nonfair-lock" class="nav-link text-gray-700 hover:text-indigo-700">非公平锁</a>
                    <a href="#comparison" class="nav-link text-gray-700 hover:text-indigo-700">对比分析</a>
                </div>
                <button class="md:hidden text-gray-700">
                    <i class="fas fa-bars text-xl"></i>
                </button>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <main class="container mx-auto max-w-5xl px-4 py-12">
        <!-- Introduction -->
        <section id="introduction" class="mb-16">
            <div class="drop-cap mb-8 text-lg leading-relaxed">
                当我们在讨论并发编程时，线程之间的协调和同步是一个极为重要的课题。在多线程环境中，锁机制用于确保同一时间内，只有一个线程可以访问共享资源，从而避免数据不一致和竞争条件。正因为锁在并发控制中的重要性，理解锁的不同类型和特性就显得尤为关键。
            </div>
            <div class="grid md:grid-cols-2 gap-8 mb-8">
                <div class="card bg-white p-6 shadow-md">
                    <div class="flex items-center mb-4">
                        <div class="bg-indigo-100 p-3 rounded-full mr-4">
                            <i class="fas fa-balance-scale text-indigo-600 text-xl"></i>
                        </div>
                        <h3 class="text-xl font-bold">公平锁</h3>
                    </div>
                    <p class="text-gray-700">确保线程获取锁的顺序是严格按照请求顺序来执行的，避免"饥饿"现象，使得所有线程都能公平地获得资源。</p>
                </div>
                <div class="card bg-white p-6 shadow-md">
                    <div class="flex items-center mb-4">
                        <div class="bg-purple-100 p-3 rounded-full mr-4">
                            <i class="fas fa-bolt text-purple-600 text-xl"></i>
                        </div>
                        <h3 class="text-xl font-bold">非公平锁</h3>
                    </div>
                    <p class="text-gray-700">更加灵活和高效，允许线程插队获取锁，从而提高系统的吞吐量，但同时也带来了可能导致某些线程长时间等待的问题。</p>
                </div>
            </div>
            <img src="https://cdn.nlark.com/yuque/0/2024/png/21449790/1723520219159-2b0070fe-0356-4e0a-aed6-f325264ab680.png" alt="锁机制示意图" class="w-full rounded-lg shadow-lg">
        </section>

        <!-- Basic Concepts -->
        <section id="basic-concepts" class="mb-16">
            <h2 class="text-3xl font-bold mb-6 font-serif border-l-4 border-indigo-600 pl-4">基本概念</h2>
            <p class="mb-6 text-lg leading-relaxed">在并发编程中，锁是控制多个线程对共享资源访问的重要机制。公平锁和非公平锁是锁的两种策略，它们的主要区别在于对线程获取锁的顺序控制方式。</p>
            <img src="https://cdn.nlark.com/yuque/0/2024/png/21449790/1723520273373-28357c9f-19fd-4da6-81f7-aa804a3b6f9a.png" alt="公平锁与非公平锁概念图" class="w-full rounded-lg shadow-lg mb-8">
            
            <div class="grid md:grid-cols-2 gap-8">
                <div class="card bg-white p-6 shadow-md">
                    <div class="flex items-center mb-4">
                        <div class="bg-indigo-100 p-3 rounded-full mr-4">
                            <i class="fas fa-check-circle text-indigo-600 text-xl"></i>
                        </div>
                        <h3 class="text-xl font-bold">公平锁 (Fair Lock)</h3>
                    </div>
                    <p class="mb-4 text-gray-700">公平锁，顾名思义，就是保证公平性的锁。它确保线程在获取锁时严格按照它们请求锁的顺序进行，即"先到先得"的原则。</p>
                    <div class="code-block">
                        <span class="language">Java</span>
                        <pre><code>ReentrantLock lock = new ReentrantLock(true);</code></pre>
                    </div>
                    <p class="mt-4 text-gray-700">这种实现方式在某些场景下非常重要，尤其是在对资源访问的公平性要求较高的情况下，比如银行系统中的账户操作。</p>
                </div>
                <div class="card bg-white p-6 shadow-md">
                    <div class="flex items-center mb-4">
                        <div class="bg-purple-100 p-3 rounded-full mr-4">
                            <i class="fas fa-random text-purple-600 text-xl"></i>
                        </div>
                        <h3 class="text-xl font-bold">非公平锁 (Unfair Lock)</h3>
                    </div>
                    <p class="mb-4 text-gray-700">非公平锁则是另一个极端。它不考虑线程请求锁的顺序，当锁释放时，任何一个线程都有机会获取锁。</p>
                    <div class="code-block">
                        <span class="language">Java</span>
                        <pre><code>ReentrantLock lock = new ReentrantLock(); // 默认是非公平锁</code></pre>
                    </div>
                    <p class="mt-4 text-gray-700">这种实现更适合那些对性能有高要求，但对资源访问公平性要求不高的场景，如某些高并发的应用程序中。</p>
                </div>
            </div>
        </section>

        <div class="divider"></div>

        <!-- Fair Lock Implementation -->
        <section id="fair-lock" class="mb-16">
            <h2 class="text-3xl font-bold mb-6 font-serif border-l-4 border-indigo-600 pl-4">公平锁的实现</h2>
            <p class="mb-6 text-lg leading-relaxed">公平锁的实现主要集中在如何保证线程按请求锁的顺序依次获取锁。在Java中，公平锁的实现通常依赖于<code>ReentrantLock</code>，它通过内部的队列机制来实现公平性。</p>
            <img src="https://cdn.nlark.com/yuque/0/2024/png/21449790/1723520444851-1c5a7e94-c740-45a6-bd88-82305edf9232.png" alt="公平锁实现示意图" class="w-full rounded-lg shadow-lg mb-8">
            
            <div class="grid md:grid-cols-2 gap-8 mb-8">
                <div>
                    <h3 class="text-2xl font-bold mb-4 flex items-center">
                        <i class="fas fa-project-diagram text-indigo-600 mr-3"></i>
                        内部数据结构
                    </h3>
                    <p class="text-gray-700 mb-4">公平锁的实现依赖于一个FIFO（先进先出）的队列结构。在<code>ReentrantLock</code>中，这个队列是通过 <code>AbstractQueuedSynchronizer</code>（简称AQS）来实现的。</p>
                    <p class="text-gray-700">AQS内部使用了一个双向链表来维护等待获取锁的线程队列。每个节点（Node）表示一个等待获取锁的线程，节点按照线程请求锁的顺序加入队列。</p>
                </div>
                <div>
                    <h3 class="text-2xl font-bold mb-4 flex items-center">
                        <i class="fas fa-lock text-indigo-600 mr-3"></i>
                        锁的获取
                    </h3>
                    <p class="text-gray-700 mb-4">当一个线程尝试获取锁时，<code>ReentrantLock</code>会首先检查当前锁是否可用：</p>
                    <ul class="list-disc pl-6 mb-4 text-gray-700 space-y-2">
                        <li>如果锁是可用的，且队列为空，则线程直接获取锁</li>
                        <li>如果锁不可用，或者有其他线程在等待，则线程会被加入到AQS的队列中，按照FIFO的顺序等待获取锁</li>
                    </ul>
                </div>
            </div>

            <div class="mb-8">
                <h3 class="text-2xl font-bold mb-4 flex items-center">
                    <i class="fas fa-code text-indigo-600 mr-3"></i>
                    核心代码实现
                </h3>
                <div class="code-block mb-4">
                    <span class="language">Java</span>
                    <pre><code>protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
        if (!hasQueuedPredecessors() && 
            compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    } else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0) // overflow
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}</code></pre>
                </div>
                <p class="text-gray-700">这里的 <code>hasQueuedPredecessors()</code> 方法用于判断当前线程在队列中是否有前置节点，如果没有，则允许该线程获取锁。否则，线程将被阻塞，直到轮到它为止。</p>
            </div>

            <div class="grid md:grid-cols-2 gap-8">
                <div>
                    <h3 class="text-2xl font-bold mb-4 flex items-center">
                        <i class="fas fa-unlock text-indigo-600 mr-3"></i>
                        锁的释放
                    </h3>
                    <p class="text-gray-700 mb-4">当持有锁的线程调用 <code>unlock()</code> 释放锁时，锁的状态会被设置为可用（即将 <code>state</code> 设置为0）。此时，AQS会通知队列中的下一个线程准备获取锁。</p>
                    <div class="code-block">
                        <span class="language">Java</span>
                        <pre><code>public final boolean release(int releases) {
    if (tryRelease(releases)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    }
    return false;
}</code></pre>
                    </div>
                </div>
                <div>
                    <h3 class="text-2xl font-bold mb-4 flex items-center">
                        <i class="fas fa-shield-alt text-indigo-600 mr-3"></i>
                        公平性保障
                    </h3>
                    <p class="text-gray-700 mb-4">在<code>ReentrantLock</code>中，公平锁的公平性是通过队列严格的FIFO顺序和 <code>hasQueuedPredecessors()</code> 方法实现的。</p>
                    <p class="text-gray-700">具体来说，<code>hasQueuedPredecessors()</code> 判断当前线程是否有前置线程，如果有，则当前线程必须排队等待，直到前置线程释放锁。这种机制保证了线程获取锁的顺序是公平的。</p>
                </div>
            </div>

            <div class="mt-8 grid md:grid-cols-2 gap-8">
                <div class="bg-indigo-50 p-6 rounded-lg">
                    <h4 class="text-xl font-bold mb-3 text-indigo-800">优点</h4>
                    <ul class="list-disc pl-6 text-gray-700 space-y-2">
                        <li>消除线程饥饿，保证所有线程都能按顺序获取锁</li>
                        <li>适用于关键场景，如银行账户操作、订单处理系统</li>
                        <li>确保资源分配的公平性</li>
                    </ul>
                </div>
                <div class="bg-red-50 p-6 rounded-lg">
                    <h4 class="text-xl font-bold mb-3 text-red-800">缺点</h4>
                    <ul class="list-disc pl-6 text-gray-700 space-y-2">
                        <li>性能较低，特别是在高并发环境下</li>
                        <li>增加了线程调度的开销</li>
                        <li>可能导致更高的上下文切换次数</li>
                    </ul>
                </div>
            </div>
        </section>

        <div class="divider"></div>

        <!-- Non-Fair Lock Implementation -->
        <section id="nonfair-lock" class="mb-16">
            <h2 class="text-3xl font-bold mb-6 font-serif border-l-4 border-purple-600 pl-4">非公平锁的实现</h2>
            <p class="mb-6 text-lg leading-relaxed">非公平锁相较于公平锁而言，主要在于它并不严格按照线程请求锁的顺序来分配锁资源，这种设计通常是为了提升系统的吞吐量。在Java中，<code>ReentrantLock</code> 可以通过构造函数参数来选择公平锁或非公平锁，其中非公平锁是默认选项。</p>
            <img src="https://cdn.nlark.com/yuque/0/2024/png/21449790/1723520569454-cc01eb03-6553-4d2a-82eb-5396d507aff5.png" alt="非公平锁实现示意图" class="w-full rounded-lg shadow-lg mb-8">
            
            <div class="grid md:grid-cols-2 gap-8 mb-8">
                <div>
                    <h3 class="text-2xl font-bold mb-4 flex items-center">
                        <i class="fas fa-info-circle text-purple-600 mr-3"></i>
                        基本概念
                    </h3>
                    <p class="text-gray-700 mb-4">非公平锁不保证获取锁的顺序，因此可能会出现"插队"现象，即当一个线程请求锁时，它有可能在队列前面还有其他等待线程的情况下直接获取到锁。</p>
                    <p class="text-gray-700">这样可以减少上下文切换的开销，从而提升系统的整体性能，但也可能导致某些线程长期等待锁，造成线程"饥饿"。</p>
                </div>
                <div>
                    <h3 class="text-2xl font-bold mb-4 flex items-center">
                        <i class="fas fa-exchange-alt text-purple-600 mr-3"></i>
                        锁的获取流程
                    </h3>
                    <p class="text-gray-700">在<code>ReentrantLock</code>的非公平锁实现中，当一个线程尝试获取锁时，它首先会直接尝试通过 <code>compareAndSetState</code> 来获取锁，无需检查队列中是否有其他线程在等待。只有在直接获取锁失败后，才会将线程放入等待队列。</p>
                </div>
            </div>

            <div class="mb-8">
                <h3 class="text-2xl font-bold mb-4 flex items-center">
                    <i class="fas fa-code text-purple-600 mr-3"></i>
                    核心代码实现
                </h3>
                <div class="code-block mb-4">
                    <span class="language">Java</span>
                    <pre><code>final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
        if (compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    } else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0) // overflow
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}</code></pre>
                </div>
                <p class="text-gray-700">在这个实现中，<code>nonfairTryAcquire()</code> 方法直接尝试获取锁，如果锁当前可用（即 <code>state == 0</code>），线程就会立即获取锁，并且不会去检查是否有其他线程在等待。这是非公平锁的关键所在。</p>
            </div>

            <div class="mb-8">
                <h3 class="text-2xl font-bold mb-4 flex items-center">
                    <i class="fas fa-unlock-alt text-purple-600 mr-3"></i>
                    锁的释放流程
                </h3>
                <p class="text-gray-700 mb-4">非公平锁和公平锁在锁释放时的行为是类似的。当持有锁的线程释放锁时，锁的状态被重置为0，AQS 会唤醒队列中的下一个线程。</p>
                <div class="code-block">
                    <span class="language">Java</span>
                    <pre><code>public final boolean release(int releases) {
    if (tryRelease(releases)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    }
    return false;
}</code></pre>
                </div>
            </div>

            <div class="grid md:grid-cols-2 gap-8 mb-8">
                <div>
                    <h3 class="text-2xl font-bold mb-4 flex items-center">
                        <i class="fas fa-lightbulb text-purple-600 mr-3"></i>
                        实现原理
                    </h3>
                    <p class="text-gray-700">非公平锁的设计旨在最大化系统吞吐量。通过允许插队的机制，非公平锁减少了上下文切换和线程切换的开销，提升了锁的利用率和系统的并发性能。</p>
                    <p class="text-gray-700 mt-4">具体来说，非公平锁直接通过CAS操作尝试获取锁，不会检查队列中的其他等待线程，这减少了线程调度的开销。在多核环境下，这种设计可以充分利用系统资源，特别是在高并发场景下，表现出更好的吞吐量。</p>
                </div>
                <div>
                    <h3 class="text-2xl font-bold mb-4 flex items-center">
                        <i class="fas fa-cog text-purple-600 mr-3"></i>
                        Java中的配置
                    </h3>
                    <p class="text-gray-700 mb-4">在Java中，可以通过<code>ReentrantLock</code>的构造函数来选择是否使用公平锁。默认情况下，<code>ReentrantLock</code>使用非公平锁：</p>
                    <div class="code-block">
                        <span class="language">Java</span>
                        <pre><code>Lock lock = new ReentrantLock(); // 默认是非公平锁
Lock fairLock = new ReentrantLock(true); // 公平锁</code></pre>
                    </div>
                    <p class="mt-4 text-gray-700">通过这种配置，开发者可以根据实际业务需求来选择合适的锁类型，以在公平性和性能之间找到平衡。</p>
                </div>
            </div>

            <div class="grid md:grid-cols-2 gap-8">
                <div class="bg-green-50 p-6 rounded-lg">
                    <h4 class="text-xl font-bold mb-3 text-green-800">优点</h4>
                    <ul class="list-disc pl-6 text-gray-700 space-y-2">
                        <li>高吞吐量：减少线程上下文切换，提升系统的整体吞吐量</li>
                        <li>简单实现：直接通过CAS操作获取锁，减少了额外的队列检查操作</li>
                    </ul>
                </div>
                <div class="bg-yellow-50 p-6 rounded-lg">
                    <h4 class="text-xl font-bold mb-3 text-yellow-800">缺点</h4>
                    <ul class="list-disc pl-6 text-gray-700 space-y-2">
                        <li>线程饥饿风险：可能导致某些线程长期得不到锁</li>
                        <li>不适合需要严格顺序的场景</li>
                    </ul>
                </div>
            </div>

            <div class="mt-8 bg-white p-6 rounded-lg shadow-md">
                <h3 class="text-2xl font-bold mb-4 flex items-center">
                    <i class="fas fa-laptop-code text-purple-600 mr-3"></i>
                    应用场景
                </h3>
                <p class="text-gray-700 mb-4">非公平锁通常用于对吞吐量要求较高的系统中，例如：</p>
                <div class="grid md:grid-cols-3 gap-6">
                    <div class="flex items-start">
                        <div class="bg-purple-100 p-3 rounded-full mr-4">
                            <i class="fas fa-globe text-purple-600"></i>
                        </div>
                        <div>
                            <h4 class="font-bold mb-2">高并发Web服务</h4>
                            <p class="text-gray-700 text-sm">处理大量并发请求的Web服务器</p>
                        </div>
                    </div>
                    <div class="flex items-start">
                        <div class="bg-purple-100 p-3 rounded-full mr-4">
                            <i class="fas fa-tasks text-purple-600"></i>
                        </div>
                        <div>
                            <h4 class="font-bold mb-2">任务调度系统</h4>
                            <p class="text-gray-700 text-sm">需要快速处理大量短任务的系统</p>
                        </div>
                    </div>
                    <div class="flex items-start">
                        <div class="bg-purple-100 p-3 rounded-full mr-4">
                            <i class="fas fa-bolt text-purple-600"></i>
                        </div>
                        <div>
                            <h4 class="font-bold mb-2">高性能API</h4>
                            <p class="text-gray-700 text-sm">对响应时间要求严格的API服务</p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <div class="divider"></div>

        <!-- Comparison -->
        <section id="comparison" class="mb-16">
            <h2 class="text-3xl font-bold mb-6 font-serif border-l-4 border-blue-600 pl-4">公平锁与非公平锁的比较</h2>
            <p class="mb-8 text-lg leading-relaxed">公平锁和非公平锁在多线程编程中是两个重要的概念，它们代表了不同的线程调度策略。在高并发环境下，选择合适的锁类型对系统性能、响应时间以及线程公平性有着直接的影响。</p>
            
            <div class="mermaid-container mb-8">
                <div class="mermaid">
                    gantt
                        title 公平锁 vs 非公平锁性能对比
                        dateFormat  X
                        axisFormat %s
                        section 公平锁
                        线程1: 0, 5
                        线程2: 5, 5
                        线程3: 10, 5
                        section 非公平锁
                        线程1: 0, 3
                        线程3: 3, 4
                        线程2: 7, 3
                </div>
            </div>

            <div class="grid md:grid-cols-2 gap-8 mb-8">
                <div>
                    <h3 class="text-2xl font-bold mb-4 flex items-center">
                        <i class="fas fa-balance-scale-right text-blue-600 mr-3"></i>
                        定义与基本概念
                    </h3>
                    <div class="space-y-6">
                        <div>
                            <h4 class="font-bold mb-2 text-indigo-700">公平锁 (Fair Lock)</h4>
                            <p class="text-gray-700">公平锁确保线程按照请求锁的顺序来获取锁。它通过队列机制确保先请求锁的线程优先获取锁，避免线程饥饿。</p>
                        </div>
                        <div>
                            <h4 class="font-bold mb-2 text-purple-700">非公平锁 (Non-Fair Lock)</h4>
                            <p class="text-gray-700">非公平锁则不保证线程获取锁的顺序。任何线程都可以直接尝试获取锁，即使其他线程已经在等待队列中。</p>
                        </div>
                    </div>
                </div>
                <div>
                    <h3 class="text-2xl font-bold mb-4 flex items-center">
                        <i class="fas fa-cogs text-blue-600 mr-3"></i>
                        实现机制
                    </h3>
                    <div class="space-y-6">
                        <div>
                            <h4 class="font-bold mb-2 text-indigo-700">公平锁</h4>
                            <p class="text-gray-700">基于先进先出 (FIFO) 队列实现。线程请求锁时，如果锁被占用，该线程会被放置在等待队列的末尾。锁释放时，最先进入队列的线程会被优先唤醒。</p>
                        </div>
                        <div>
                            <h4 class="font-bold mb-2 text-purple-700">非公平锁</h4>
                            <p class="text-gray-700">线程直接通过CAS操作尝试获取锁，如果成功则立即进入临界区。如果失败，线程才会进入等待队列。允许插队，减少了队列检查和线程调度的开销。</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="mb-8">
                <h3 class="text-2xl font-bold mb-6 flex items-center">
                    <i class="fas fa-tachometer-alt text-blue-600 mr-3"></i>
                    性能对比
                </h3>
                <div class="grid md:grid-cols-2 gap-8">
                    <div class="bg-indigo-50 p-6 rounded-lg">
                        <h4 class="text-xl font-bold mb-4 text-indigo-800">公平锁</h4>
                        <p class="text-gray-700 mb-4">由于公平锁严格按照顺序调度线程，所以在高并发环境下，可能会引入额外的开销。例如：</p>
                        <ul class="list-disc pl-6 text-gray-700 space-y-2">
                            <li>线程频繁上下文切换</li>
                            <li>队列管理和调度的开销较大</li>
                            <li>锁的获取速度较慢，影响系统吞吐量</li>
                            <li>在多核CPU中可能降低整体并行度</li>
                        </ul>
                    </div>
                    <div class="bg-purple-50 p-6 rounded-lg">
                        <h4 class="text-xl font-bold mb-4 text-purple-800">非公平锁</h4>
                        <p class="text-gray-700 mb-4">非公平锁通过允许线程插队来减少上下文切换和队列管理的开销。在高并发环境下：</p>
                        <ul class="list-disc pl-6 text-gray-700 space-y-2">
                            <li>能够显著提升系统的吞吐量</li>
                            <li>减少线程等待时间</li>
                            <li>可能导致线程"饥饿"现象</li>
                            <li>在高竞争情况下表现更好</li>
                        </ul>
                    </div>
                </div>
            </div>

            <div class="mb-8">
                <h3 class="text-2xl font-bold mb-6 flex items-center">
                    <i class="fas fa-laptop-house text-blue-600 mr-3"></i>
                    应用场景
                </h3>
                <div class="grid md:grid-cols-2 gap-8">
                    <div class="bg-white p-6 rounded-lg shadow-sm border border-indigo-100">
                        <h4 class="text-xl font-bold mb-4 text-indigo-700">公平锁适用场景</h4>
                        <ul class="space-y-4">
                            <li class="flex items-start">
                                <div class="bg-indigo-100 p-2 rounded-full mr-3">
                                    <i class="fas fa-university text-indigo-600"></i>
                                </div>
                                <div>
                                    <h5 class="font-bold">银行账户转账系统</h5>
                                    <p class="text-gray-700 text-sm">要求严格按照请求顺序处理交易，避免账户不一致</p>
                                </div>
                            </li>
                            <li class="flex items-start">
                                <div class="bg-indigo-100 p-2 rounded-full mr-3">
                                    <i class="fas fa-ticket-alt text-indigo-600"></i>
                                </div>
                                <div>
                                    <h5 class="font-bold">票务系统</h5>
                                    <p class="text-gray-700 text-sm">确保订票请求按顺序处理，避免超卖</p>
                                </div>
                            </li>
                            <li class="flex items-start">
                                <div class="bg-indigo-100 p-2 rounded-full mr-3">
                                    <i class="fas fa-server text-indigo-600"></i>
                                </div>
                                <div>
                                    <h5 class="font-bold">高优先级任务调度</h5>
                                    <p class="text-gray-700 text-sm">确保高优先级任务按顺序获取资源</p>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <div class="bg-white p-6 rounded-lg shadow-sm border border-purple-100">
                        <h4 class="text-xl font-bold mb-4 text-purple-700">非公平锁适用场景</h4>
                        <ul class="space-y-4">
                            <li class="flex items-start">
                                <div class="bg-purple-100 p-2 rounded-full mr-3">
                                    <i class="fas fa-server text-purple-600"></i>
                                </div>
                                <div>
                                    <h5 class="font-bold">Web服务器</h5>
                                    <p class="text-gray-700 text-sm">处理大量并发HTTP请求</p>
                                </div>
                            </li>
                            <li class="flex items-start">
                                <div class="bg-purple-100 p-2 rounded-full mr-3">
                                    <i class="fas fa-bolt text-purple-600"></i>
                                </div>
                                <div>
                                    <h5 class="font-bold">高并发API</h5>
                                    <p class="text-gray-700 text-sm">需要快速响应大量API调用</p>
                                </div>
                            </li>
                            <li class="flex items-start">
                                <div class="bg-purple-100 p-2 rounded-full mr-3">
                                    <i class="fas fa-microchip text-purple-600"></i>
                                </div>
                                <div>
                                    <h5 class="font-bold">计算密集型任务</h5>
                                    <p class="text-gray-700 text-sm">短时间占用锁的计算任务</p>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>

            <div class="bg-white p-6 rounded-lg shadow-md">
                <h3 class="text-2xl font-bold mb-6">优缺点总结</h3>
                <div class="overflow-x-auto">
                    <table class="comparison-table">
                        <thead>
                            <tr>
                                <th></th>
                                <th class="text-indigo-700">公平锁</th>
                                <th class="text-purple-700">非公平锁</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="font-medium">优点</td>
                                <td>
                                    <ul class="list-disc pl-5 space-y-1">
                                        <li>避免线程饥饿</li>
                                        <li>确保请求顺序</li>
                                        <li>适合顺序敏感场景</li>
                                    </ul>
                                </td>
                                <td>
                                    <ul class="list-disc pl-5 space-y-1">
                                        <li>高性能</li>
                                        <li>高吞吐量</li>
                                        <li>减少上下文切换</li>
                                    </ul>
                                </td>
                            </tr>
                            <tr>
                                <td class="font-medium">缺点</td>
                                <td>
                                    <ul class="list-disc pl-5 space-y-1">
                                        <li>性能较低</li>
                                        <li>调度开销大</li>
                                        <li>高并发下表现不佳</li>
                                    </ul>
                                </td>
                                <td>
                                    <ul class="list-disc pl-5 space-y-1">
                                        <li>可能导致线程饥饿</li>
                                        <li>不适合顺序敏感场景</li>
                                    </ul>
                                </td>
                            </tr>
                            <tr>
                                <td class="font-medium">典型应用</td>
                                <td>银行系统、票务系统</td>
                                <td>Web服务器、API服务</td>
                            </tr>
                            <tr>
                                <td class="font-medium">Java实现</td>
                                <td><code>new ReentrantLock(true)</code></td>
                                <td><code>new ReentrantLock()</code></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="mt-8 bg-blue-50 p-6 rounded-lg">
                <h3 class="text-2xl font-bold mb-4 text-blue-800 flex items-center">
                    <i class="fas fa-lightbulb mr-3"></i>
                    决策建议
                </h3>
                <p class="text-gray-700 mb-4">在实际开发中，选择公平锁还是非公平锁应根据具体业务场景来决定：</p>
                <div class="grid md:grid-cols-2 gap-6">
                    <div class="bg-white p-4 rounded-lg shadow-sm">
                        <div class="flex items-center mb-3">
                            <div class="bg-indigo-100 p-2 rounded-full mr-3">
                                <i class="fas fa-check-circle text-indigo-600"></i>
                            </div>
                            <h4 class="font-bold">选择公平锁</h4>
                        </div>
                        <p class="text-gray-700 text-sm">当系统对并发处理的顺序性要求严格，并且需要避免线程饥饿时，如金融交易、票务系统等关键业务场景。</p>
                    </div>
                    <div class="bg-white p-4 rounded-lg shadow-sm">
                        <div class="flex items-center mb-3">
                            <div class="bg-purple-100 p-2 rounded-full mr-3">
                                <i class="fas fa-bolt text-purple-600"></i>
                            </div>
                            <h4 class="font-bold">选择非公平锁</h4>
                        </div>
                        <p class="text-gray-700 text-sm">当系统需要高吞吐量和快速响应，并且能够接受一定程度的线程饥饿时，如高并发Web服务、API网关等。</p>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <script>
        mermaid.initialize({
            startOnLoad: true,
            theme: 'default',
            flowchart: {
                useMaxWidth: true,
                htmlLabels: true,
                curve: 'basis'
            },
            gantt: {
                axisFormat: '%H:%M:%S'
            }
        });
        
        // 平滑滚动
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                document.querySelector(this.getAttribute('href')).scrollIntoView({
                    behavior: 'smooth'
                });
            });
        });
        
        // 导航栏高亮
        window.addEventListener('scroll', function() {
            const sections = document.querySelectorAll('section');
            const navLinks = document.querySelectorAll('nav a');
            
            let current = '';
            sections.forEach(section => {
                const sectionTop = section.offsetTop;
                const sectionHeight = section.clientHeight;
                if (pageYOffset >= sectionTop - 100) {
                    current = section.getAttribute('id');
                }
            });
            
            navLinks.forEach(link => {
                link.classList.remove('text-indigo-700');
                if (link.getAttribute('href') === '#' + current) {
                    link.classList.add('text-indigo-700');
                }
            });
        });
    </script>
</body>
</html>
```